let server = require("express")();
let expressStatic = require("express-static")
let mysql = require("mysql")
const port = 80;

let sql = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'school',
    timezone: "08:00"
});

sql.connect();

//查找功能
server.get("/getstudentList", (request, response) => {
        sql.query(`SELECT * FROM students`, (error, data) => {
            if (error) {
                console.log(error)
                response.send("error")
            } else {
                response.send(data)
            }
        })
    })
    //删除功能
server.get("/deleteStudent", (request, response) => {
        sql.query(`DELETE FROM students WHERE id=${request.query.id}`, (error, data) => {
            if (error) {
                console.log(error)
                response.send("error")
            } else {
                response.send("success")
            }
        })
    })
    //添加功能
server.get("/addStudent", (request, response) => {
        let p = request.query;
        sql.query(`INSERT INTO students (name,age,sex,city,joinData) VALUES ("${p.name}","${p.age}","${p.sex}","${p.city}","${p.joinDate}")`, (error, data) => {
            console.log(error)
            if (error) {
                console.log(error)
                response.send("error")
            } else {
                response.send("success")
                console.log(`新增学生${p.name}操作成功`)
            }
        })
    })
    //修改功能
server.get("/editStudent", (request, response) => {
    let p = request.query;
    sql.query(`Update students  Set name="${p.name}",age= ${p.age},sex="${p.sex}",city="${p.city}",joinData="${p.joinDate}" Where id=${p.id}`, (error, data) => {
        // console.log(error)
        if (error) {
            console.log(error)
            response.send("error")
        } else {
            response.send("success")
            console.log(`修改学生${p.name}操作成功`)
        }
    })
})

server.use(expressStatic(__dirname + '/static'))

console.log(`server is running at ${port}`)
server.listen(port);